/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "QxMainWindow.hpp"
#include "QxMenuManager.hpp"
#include "QxColors.hpp"
#include "QxDockItem.hpp"
#include "QxDemoTextItem.hpp"
#include "QxImageItem.hpp"
#include "QxDemoItem.hpp"
#include "QxDemoScene.hpp"

#ifndef QT_NO_OPENGL
#include <QGLWidget>
#endif
//#define QT_NO_OPENGL

QxMainWindow::QxMainWindow( QWidget* parent ) : QGraphicsView( parent ), updateTimer( this )
{
  this->currentFps  = QxColors::fps;
  this->loop        = false;
  this->fpsMedian   = -1;
  this->fpsLabel    = 0;
  this->pausedLabel = 0;
  this->doneAdapt   = false;
  this->useTimer    = false;
  this->companyLogo = 0;
  this->qtLogo      = 0;
  this->updateTimer.setSingleShot( true );
  this->setupWidget();
  this->setupScene();
  this->setupSceneItems();
  this->drawBackgroundToPixmap();
}

QxMainWindow::~QxMainWindow()
{
  delete this->companyLogo;
  delete this->qtLogo;
}

void QxMainWindow::setupWidget()
{
  QRect screenRect = QApplication::desktop()->screenGeometry( QApplication::desktop()->primaryScreen() );
  QRect windowRect(0, 0, 800, 600);
  if( screenRect.width() < 800 ) {
    windowRect.setWidth( screenRect.width() );
  }
  if( screenRect.height() < 600 ) {
    windowRect.setHeight( screenRect.height() );
  }
  windowRect.moveCenter( screenRect.center() );
  this->setGeometry( windowRect );
  this->setMinimumSize( 80, 60 );
  setWindowTitle( tr( "Qt Examples and Demos" ) );
  setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
  setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
  setFrameStyle( QFrame::NoFrame );
  this->setRenderingSystem();
  connect( &this->updateTimer, SIGNAL(timeout()), this, SLOT( tick() ) );
}

void QxMainWindow::setRenderingSystem()
{
  QWidget* viewport = 0;

#ifndef QT_NO_OPENGL
  if( QxColors::openGlRendering ) {
    QGLWidget* glw = new QGLWidget( QGLFormat(QGL::SampleBuffers) );
    if( QxColors::noScreenSync ) {
      glw->format().setSwapInterval(0);
    }
    glw->setAutoFillBackground( false );
    viewport = glw;
    setCacheMode( QGraphicsView::CacheNone );
    if( QxColors::verbose ) {
      qDebug() << "- using OpenGL";
    }
  } else // software rendering
#endif
  {
    // software rendering
    viewport = new QWidget;
    setCacheMode( QGraphicsView::CacheBackground );
    if( QxColors::verbose ) {
      qDebug() << "- using software rendering";
    }
  }

  setViewport( viewport );
}

void QxMainWindow::start()
{
  this->switchTimerOnOff( true );
  this->demoStartTime.restart();
  QxMenuManager::instance()->itemSelected( QxMenuManager::ROOT, QxColors::rootMenuName );
  if( QxColors::verbose ) {
    qDebug( "- starting demo" );
  }
}

void QxMainWindow::enableMask( bool enable )
{
  if( !enable || QxColors::noWindowMask ) {
    this->clearMask();
  } else {
    QPolygon region;
    region.setPoints(9,
                     // north side:
                     0, 0,
                     800, 0,
                     // east side:
                     // 800, 70,
                     // 790, 90,
                     // 790, 480,
                     // 800, 500,
                     800, 600,
                     // south side:
                     700, 600,
                     670, 590,
                     130, 590,
                     100, 600,
                     0, 600,
                     // west side:
                     // 0, 550,
                     // 10, 530,
                     // 10, 520,
                     // 0, 520,
                     0, 0);
    this->setMask(QRegion(region));
  }
}

void QxMainWindow::setupScene()
{
  this->scene = new QxDemoScene( this );
  this->scene->setSceneRect( 0, 0, 800, 600 );
  setScene( this->scene );
  this->scene->setItemIndexMethod( QGraphicsScene::NoIndex );
}

void QxMainWindow::drawItems( QPainter* painter, int numItems, QGraphicsItem** items, const QStyleOptionGraphicsItem* options )
{
  QGraphicsView::drawItems( painter, numItems, items, options );
}

void QxMainWindow::switchTimerOnOff( bool on )
{
  bool ticker = QxMenuManager::instance()->ticker() && QxMenuManager::instance()->ticker()->scene();
  if( ticker ) {
    QxMenuManager::instance()->ticker()->tickOnPaint = !on || QxColors::noTimerUpdate;
  }

  if( on && !QxColors::noTimerUpdate ){
    this->useTimer = true;
    this->setViewportUpdateMode( QGraphicsView::NoViewportUpdate );
    this->fpsTime = QTime::currentTime();
    this->updateTimer.start( int(1000 / QxColors::fps) );
  } else{
    this->useTimer = false;
    this->updateTimer.stop();
    if( QxColors::softwareRendering ) {
      if( QxColors::noTicker ) {
        this->setViewportUpdateMode( QGraphicsView::MinimalViewportUpdate );
      } else {
        this->setViewportUpdateMode( QGraphicsView::SmartViewportUpdate );
      }
    } else {
      this->setViewportUpdateMode( QGraphicsView::FullViewportUpdate );
    }
  }
}

bool QxMainWindow::measureFps()
{
  // Calculate time diff:
  float t = this->fpsTime.msecsTo( QTime::currentTime() );
  if( t == 0 ) {
    t = 0.01f;
  }
  this->currentFps = (1000.0f / t);
  this->fpsHistory += this->currentFps;
  this->fpsTime = QTime::currentTime();

  // Calculate median:
  int size = this->fpsHistory.size();
  if( size == 10 ){
    qSort(this->fpsHistory.begin(), this->fpsHistory.end());
    this->fpsMedian = this->fpsHistory.at(int(size/2));
    if( this->fpsMedian == 0 ) {
      this->fpsMedian = 0.01f;
    }
    this->fpsHistory.clear();
    return true;
  }
  return false;
}

/**
    Used for adaption in case things are so slow
    that no median  yet has been calculated
*/
void QxMainWindow::forceFpsMedianCalculation()
{
  if( this->fpsMedian != -1 ) {
    return;
  }

  int size = this->fpsHistory.size();
  if( size == 0 ){
    this->fpsMedian = 0.01f;
    return;
  }

  qSort( this->fpsHistory.begin(), this->fpsHistory.end() );
  this->fpsMedian = this->fpsHistory.at( int(size/2) );
  if( this->fpsMedian == 0 ) {
    this->fpsMedian = 0.01f;
  }
}

void QxMainWindow::tick()
{
  bool medianChanged = this->measureFps();
  this->checkAdapt();

  if( medianChanged && this->fpsLabel && QxColors::showFps ) {
    this->fpsLabel->setText( QString("FPS: ") + QString::number(int(this->currentFps)) );
  }

  if( QxMenuManager::instance()->ticker() ) {
    QxMenuManager::instance()->ticker()->tick();
  }

  this->viewport()->update();
  if( this->useTimer ) {
    this->updateTimer.start( int(1000 / QxColors::fps) );
  }
}

void QxMainWindow::setupSceneItems()
{
  if( QxColors::showFps ){
    this->fpsLabel = new QxDemoTextItem( QString("FPS: --"), QxColors::buttonFont(), Qt::white, -1, this->scene, 0, QxDemoTextItem::DYNAMIC_TEXT );
    this->fpsLabel->setZValue(1000);
    this->fpsLabel->setPos( QxColors::stageStartX, 600 - QFontMetricsF(QxColors::buttonFont()).height() - 5 );
  }

  this->mainSceneRoot = new QGraphicsWidget();
  this->scene->addItem(mainSceneRoot);
  this->companyLogo = new QxImageItem( QImage(":/images/trolltech-logo.png" ), 1000, 1000, this->scene, mainSceneRoot, true, 0.5f );
  this->qtLogo = new QxImageItem( QImage( ":/images/qtlogo_small.png" ), 1000, 1000, this->scene, mainSceneRoot, true, 0.5f );
  this->companyLogo->setZValue( 100 );
  this->qtLogo->setZValue( 100 );
  this->pausedLabel = new QxDemoTextItem( QString( "PAUSED" ), QxColors::buttonFont(), Qt::white, -1, this->scene, 0 );
  this->pausedLabel->setZValue( 100 );
  QFontMetricsF fm( QxColors::buttonFont() );
  this->pausedLabel->setPos( QxColors::stageWidth - fm.width( "PAUSED" ), 590 - fm.height() );
  this->pausedLabel->setRecursiveVisible( false );
}

void QxMainWindow::checkAdapt()
{
  if( this->doneAdapt
      || QxColors::noTimerUpdate
      || this->demoStartTime.elapsed() < 2000 ) {
    return;
  }

  this->doneAdapt = true;
  this->forceFpsMedianCalculation();
  QxColors::benchmarkFps = this->fpsMedian;
  if( QxColors::verbose ) {
    qDebug() << "- benchmark:" << QString::number( QxColors::benchmarkFps ) << "FPS";
  }

  if( QxColors::noAdapt ) {
    return;
  }

  if( this->fpsMedian < 30 ){
    if( QxMenuManager::instance()->ticker() && QxMenuManager::instance()->ticker()->scene() ){
      this->scene->removeItem( QxMenuManager::instance()->ticker() );
      QxColors::noTimerUpdate = true;
      this->switchTimerOnOff( false );
      if( this->fpsLabel ) {
        this->fpsLabel->setText( QString( "FPS: (" ) + QString::number( this->fpsMedian) + QString(")") );
      }
      if( QxColors::verbose ) {
        qDebug() << "- benchmark adaption: removed ticker (fps < 30)";
      }
    }

    if( this->fpsMedian < 20 ){
      QxColors::noAnimations = true;
      if( QxColors::verbose ) {
        qDebug() << "- benchmark adaption: animations switched off (fps < 20)";
      }
    }

    QxColors::adapted = true;
  }
}

int QxMainWindow::performBenchmark()
{
  /*
    QTime time;
    time.restart();
    while (time.elapsed() < 2000)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
*/
  return 0;
}

void QxMainWindow::drawBackgroundToPixmap()
{
  const QRectF r = this->scene->sceneRect();
  this->background = QPixmap( qRound(r.width()), qRound(r.height()) );
  this->background.fill( Qt::black );
  QPainter painter( &this->background );

  if( false && QxColors::useEightBitPalette ){
    painter.fillRect( r, QxColors::sceneBg1 );
  } else {
    QImage bg( ":/images/demobg.png" );
    painter.drawImage( 0, 0, bg );
  }
}

void QxMainWindow::drawBackground( QPainter* painter, const QRectF& rect )
{
  Q_UNUSED( rect );
  painter->drawPixmap( QPoint(0, 0), this->background );
}

void QxMainWindow::showEvent( QShowEvent* event )
{
  QGraphicsView::showEvent( event );
}

void QxMainWindow::toggleFullscreen()
{
  if( this->isFullScreen() ){
    this->enableMask( true );
    this->showNormal();
    if( QxMenuManager::instance()->ticker() ) {
      QxMenuManager::instance()->ticker()->pause( false );
    }
  } else {
    this->enableMask( false );
    this->showFullScreen();
  }
}

void QxMainWindow::keyPressEvent( QKeyEvent* event )
{
  if( event->key() == Qt::Key_Escape ){
    this->loop = false;
    QApplication::quit();
  }
  else if( event->key() == Qt::Key_F1 ){
    QString s( "" );
    s += "Rendering system: ";
    if( QxColors::openGlRendering ) {
      s += "OpenGL";
    } else {
      s += "software";
    }

    s += "\nAdapt: ";
    s += QxColors::noAdapt ? "off" : "on";
    s += "\nAdaption occurred: ";
    s += QxColors::adapted ? "yes" : "no";
    s += "\nOpenGL version: ";
    s += QxColors::glVersion;
    QWidget w;
    s += "\nColor bit depth: ";
    s += QString::number(w.depth());
    s += "\nWanted FPS: ";
    s += QString::number(QxColors::fps);
    s += "\nBenchmarked FPS: ";
    s += QxColors::benchmarkFps != -1 ? QString::number( QxColors::benchmarkFps ) : "not calculated";
    s += "\nAnimations: ";
    s += QxColors::noAnimations ? "off" : "on";
    s += "\nBlending: ";
    s += QxColors::useEightBitPalette ? "off" : "on";
    s += "\nTicker: ";
    s += QxColors::noTicker ? "off" : "on";
    s += "\nPixmaps: ";
    s += QxColors::usePixmaps ? "on" : "off";
    s += "\nRescale images on resize: ";
    s += QxColors::noRescale ? "off" : "on";
    s += "\nTimer based updates: ";
    s += QxColors::noTimerUpdate ? "off" : "on";
    s += "\nSeparate loop: ";
    s += QxColors::useLoop ? "yes" : "no";
    s += "\nScreen sync: ";
    s += QxColors::noScreenSync ? "no" : "yes";
    QMessageBox::information( 0, QString( "Current configuration" ), s );
  }
  QGraphicsView::keyPressEvent( event );
}

void QxMainWindow::focusInEvent( QFocusEvent* )
{
  if( !QxColors::pause ) {
    return;
  }

  if( QxMenuManager::instance()->ticker() ) {
    QxMenuManager::instance()->ticker()->pause( false );
  }

  int code = QxMenuManager::instance()->currentMenuCode();
  if( code == QxMenuManager::ROOT || code == QxMenuManager::MENU1 ) {
    this->switchTimerOnOff(true);
  }

  this->pausedLabel->setRecursiveVisible( false );
}

void QxMainWindow::focusOutEvent( QFocusEvent* )
{
  if( !QxColors::pause ) {
    return;
  }

  if( QxMenuManager::instance()->ticker() ) {
    QxMenuManager::instance()->ticker()->pause( true );
  }

  int code = QxMenuManager::instance()->currentMenuCode();
  if( code == QxMenuManager::ROOT || code == QxMenuManager::MENU1 ) {
    this->switchTimerOnOff( false );
  }

  this->pausedLabel->setRecursiveVisible( true );
}

void QxMainWindow::resizeEvent( QResizeEvent* event )
{
  Q_UNUSED( event );

  this->resetMatrix();
  this->scale( event->size().width() / 800.0, event->size().height() / 600.0 );
  QGraphicsView::resizeEvent( event );
  QxDemoItem::setMatrix( this->matrix() );

  if( this->companyLogo ){
    const QRectF r = this->scene->sceneRect();
    QRectF ttb = this->companyLogo->boundingRect();
    this->companyLogo->setPos( int((r.width() - ttb.width()) / 2), 595 - ttb.height() );
    QRectF qtb = this->qtLogo->boundingRect();
    this->qtLogo->setPos( 802 - qtb.width(), 0 );
  }

  // Changing size will almost always
  // hurt FPS during the changing. So
  // ignore it.
  this->fpsHistory.clear();
}
